<template>
	<div>
		<div v-for="item in personList" :key="item.name">{{ item.name }}</div>
		<div>count: {{ count }}</div>
		<div>myAge: {{ myAge }}, 放大十倍: {{ addAge }}</div>
		<button type="submit" @click="handleBtn('changeUser')">修改用户信息</button>
		<div>用户信息: {{ userInfoStore.userInfo }}</div>
		<el-input v-model="inputVal" @input="emit('update:inputVal', $event)"></el-input>
	</div>
</template>
<script lang="ts" setup>
import type { Persons } from "@/interface";
import { useUserInfoStore } from "@/store/userInfo.ts";
import { storeToRefs } from "pinia";
const userInfoStore = useUserInfoStore();
// 如果要修改从useUserInfo结构出来的值需要用storeToRefs把数据变成响应式数据
// 结构赋值是将对象的属性提取出来赋值给新的变量，基本类型(string, number等等)会丢失响应式，对象类型(数组，对象)会保留响应式
const { userInfo, myAge, addAge } = storeToRefs(userInfoStore);
const emit = defineEmits(['update:inputVal'])

const props = withDefaults(
	defineProps<{
		personList: Persons;
		count: number;
		inputVal: string;
	}>(),
	{
		personList: () => [{ name: "张三", age: 10000, gender: "男" }],
		count: () => 500,
		inputVal: () => ''
	}
);
const inputVal = ref(props.inputVal);
onUnmounted(() => {
	unsubscribe(); // 取消订阅
});

const handleBtn = (type: string) => {
	switch (type) {
		case "changeUser":
			myAge.value += 1;
			userInfo.value.username = "王麻子";
			userInfoStore.$patch({
				userInfo: {
					username: "王麻子",
					age: 50,
					sex: "女"
				}
			});
			break;
		default:
			break;
	}
};

// 订阅(监听)数据变化: 如果简单的是基础类型使用watch，复杂类型使用subscribe
const unsubscribe = userInfoStore.$subscribe((mutation, state) => {
	console.log("数据变化===", mutation, state);
});

watch(() => myAge.value, e => {
	console.log("watch===123", e);
});
</script>
